var urlSTR = "";//具体操作的管理功能
var tType = "";//具体功能对应的数据库表格
var tType_id = "";//修改内容对应数据库的id
var tType_name = "";//修改数据库对应的列名
var tType_name_content = new Array();//修改的内容
var tType_work = '';//工作类型
var search_type = '';//查询目标
var bill_content = new Array();//缴费选择记录

/**
 * *************************************************************************************************************************************************
 * 具体管理功能信息显示
 * 显示数据库数据以及分页
 */
function ShowRight(url,Type) {
	urlSTR = url;
	tType = Type;
	
    change(url);
}


function showMsg(){
	
	if(tType == "bill"){
		$.ajax({
			url: "len",
			type: "POST",
			async: false,
			dataType: "json",
			data:{
				'search_type':search_type
			},
			success: function(date){
				pageCount = date;
			}
		})
	}else{
		$.ajax({
			url: "len",
			type: "POST",
			async: false,
			dataType: "json",
			data:{
				'type':tType
			},
			success: function(date){
				pageCount = date;
			}
		})
	}
	
	//分页总数量
	$('.pagination').pagination(pageCount,
			{
		callback: PageCallback,	//PageCallback() 为翻页调用次数
		prev_text:"< 上一页",
		next_text:"下一页  >",
		items_per_page: 5,
		num_edge_entries: 2,	//两侧收尾分页条目数
		num_display_entries: 10,	//连续分页主题部分分页条目数
		current_page: 0,	//当前页索引//
	})
}

function PageCallback(page_index,jq){
	
	if(tType == "bill"){
		$.ajax({
			url: "page",
			type: "POST",
			async: false,
			dataType: "json",
			data: {
				'index':page_index + 1,
				'type':tType,
				'searchType':search_type
			},
			success: function(date){
				var MSGList = date.MSGList;
				var nameChang = date.nameChang;
				var html = '';
				
				html += '<tr>';
				for(var x=0; x<nameChang.length; x++){
					html += '<th>'+nameChang[x]+'</th>';
				}
				html += '</tr>';
				document.getElementById("thead").innerHTML = html;
				
				html = '';
				
				for(var x=0; x<MSGList.length;){
					html += '<tr>';
					for(var y=0;y<4;y++,x++){
						var z = (x+1)/4-1;
						var id = ((page_index+1)*5-5)+z;
						if(y==3){
							html += '<td id="'+x+'">现金：	<input type="radio" name="'+id+'" value="现金" onclick="addContent('+id+')"></input>支票：	<input type="radio" name="'+id+'" value="支票" onclick="addContent('+id+')" ></input></td>';
						}else{
							html += '<td>'+MSGList[x]+'</td>';
						}
					}
					
					html += '</tr>';
				}
				document.getElementById("tbody").innerHTML = html;
				
			}
		});
	}else{
		$.ajax({
			url: "page",
			type: "POST",
			async: false,
			dataType: "json",
			data: {
				'index':page_index + 1,
				'type':tType
			},
			success: function(date){
				//获取绝对路径
				var curWwwPath=window.document.location.href;
				var pathName=window.document.location.pathname;
				var pos=curWwwPath.indexOf(pathName);
				var localhostPaht=curWwwPath.substring(0,pos);
				var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
				var realPath="'"+localhostPaht+projectName + "/work/change.jsp'" ;
				
				var html = '';
				var list = date.MSGList;
				var nameList = date.nameList;
				
				for(var i=0; i<list.length; i+=nameList.length){
					html += '<tr>';
					var changeID = '';
					var i_num = i;
					for(var x=0; x<nameList.length; x++,i_num++){
						if(x==0){
							changeID = list[i];
						}
						
						html += '<td>'+ list[i_num] +'</td>';
					}
					var id_num = (nameList.length)*i;
					html += '<td><button onclick="workChange('+realPath+','+changeID+')" class="dep_update_button">修改</button></td>';
					html += '</tr>';
				}
				$('#table').html(html);
			}
		})
	}
	
}


/**
 * *************************************************************************************************************************************************
 * 进入修改页面
 * 并显示修改区域
 */ 
function workChange(url,id) {
	tType_id = id;
	tType_work = '修改';
	
	dates(id);
	 change(url);
	 dates(id);
	 
	 //数据交互
	 function dates(id){
		 $.ajax({
			 url: "change",
			 type: "POST",
			 async: false,
			 dataType: "json",
			 data: {
				 'name':tType,
				 'num_id':id,
				 'work':tType_work
			 },
			 success: function(date){
				 var nameList = date.nameList;
				 var nameListChange = date.nameListChange;
				 var messagesList = date.messagesList;
				 
				 tType_name = nameList;
				 
				 add(nameListChange,messagesList,nameList);
			 }
		 })
		 //添加文本框
		 function add(nameListChange,messagesList,nameList){
			 
			 var html = '';
			 
			 html +="<tr><th>部门编号</th><th>部门名称</th><th>部门领导</th><th>部门信息</th></tr>";
			 html +="<tr>";
			 for(var i=0;i<nameListChange.length;i++){
				 if(i==0){
					 html += '<td><input type="text" type="'+nameList[i]+'" name="'+nameList[i]+'" class="input" id="'+nameList[i]+'" value="'+messagesList[i]+'" disabled></input></td>';
				 }else{
					 html += '<td><input type="text" type="'+nameList[i]+'" name="'+nameList[i]+'" class="input" id="'+nameList[i]+'" value="'+messagesList[i]+'"></input></td>';
				 }
			 }
			 html +="</tr>";
			
			 $("#data_table_show").html(html);
		 }
	 }
	 
	 
 }

//跳转修改页面
	 function change(url){
		 var xmlHttp;
       
       if (window.XMLHttpRequest) {
           // code for IE7+, Firefox, Chrome, Opera, Safari
           xmlHttp=new XMLHttpRequest();    //创建 XMLHttpRequest对象
       }
       else {
           // code for IE6, IE5
           xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
       
       xmlHttp.onreadystatechange=function() {        
           //onreadystatechange — 当readystate变化时调用后面的方法
           
           if (xmlHttp.readyState == 4) {
               //xmlHttp.readyState == 4    ——    finished downloading response
               
               if (xmlHttp.status == 200) {
                   //xmlHttp.status == 200        ——    服务器反馈正常            
                   
                   document.getElementById("right_messages").innerHTML=xmlHttp.responseText;    //重设页面中id="right_messages"的div里的内容
               }
               //错误状态处理
               else if (xmlHttp.status == 404){
                   alert("出错了☹   （错误代码：404 Not Found），……！"); 
                   /* 对404的处理 */
                   return;
               }
               else if (xmlHttp.status == 403) {  
                   alert("出错了☹   （错误代码：403 Forbidden），……"); 
                   /* 对403的处理  */ 
                   return;
               }
               else {
                   alert("出错了☹   （错误代码：" + request.status + "），……"); 
                   /* 对出现了其他错误代码所示错误的处理   */
                   return;
               }
           } 
               
         }
       
       //把请求发送到服务器上的指定文件（url指向的文件）进行处理
       xmlHttp.open("GET", url, false);        //true表示异步处理
       xmlHttp.send();
	 }



/**
 * *************************************************************************************************************************************************
 * 修改页面点击确定后返回数据显示页面
 * 并执行修改功能
 */

function doChange(){
	
	var doready = false;
	
	if(tType_work == "修改"){
		for(var i=0; i<tType_name.length; i++){
			var name_content = '';
			if(i==0){
				name_content = tType_id;
			}else{
				name_content = document.getElementById(tType_name[i]).value;
			}
			tType_name_content[i] = name_content;
		}
	}else if(tType_work == "添加"){
		for(var i=0; i<tType_name.length; i++){
			var name_content = '';
			if(i==0){
				name_content = tType_id;
			}else{
				name_content = document.getElementById(tType_name[i]).value;
			}
			tType_name_content[i] = name_content;
		}
	}
	
	//校验
	check();
	
	function check(){
		var dep_name = $("#dep_name").val().trim();
		var leading_official = $("#leading_official").val().trim();
		var description = $("#description").val().trim();
		
		var A = false;//部门名称
		var B = false;//部门领导
		var C = false;//部门信息
		
		if(dep_name !== "" && dep_name.length<=20 ){
			if(dep_name.match(/^([\u4e00-\u9fa5]*[\w]*)([\u4e00-\u9fa5]*[\w]*)+([\u4e00-\u9fa5]*[\w]*)$/)){
			A = true;
			}
		}
		if(leading_official !== "" && leading_official.match("^[\u4e00-\u9fa5]*$")||leading_official.match("^[A-Z]{1}[a-z]*$")){
			B = true;
		}
		if(description !== "" && description.length<=200 ){
			if(description.match(/^([\u4e00-\u9fa5]*[\w]*)([\u4e00-\u9fa5]*[\w]*)+([\u4e00-\u9fa5]*[\w]*)$/)){
			C = true;
			}
		}
		
		if(A && B && C){
			//后台执行修改
		    goChange();
		}else{
			alert("填写信息有误，请检查！");
		}


	}
	
//    //后台执行修改
//    goChange();
    
    function goChange(){
    	$.ajax({
    		url: "work",
    		type: "POST",
    		dataType: "json",
    		data: {
    			'type':tType,
    			'type_name':tType_name,
    			'type_name_contents':tType_name_content,
    			'workType':tType_work
    		},
    		traditional:true,
    		success: function(data){
    			doready = data.ready;
    			if(doready == true){
    				//弹出提示框
    				alert("修改部门信息成功");
    		    	change(urlSTR);
    		    	//显示修改后数据
    		        showMsg();
    		    }else{
    		    }
    		},
    		error: function(){
    			console.log("出错");
    		}
    	})
    }
    
}


//取消按钮
function delChange(){
	change(urlSTR);
	showMsg();
}

//重置文本框
function doReset(){
	if(tType_work == '修改'){
		workChange('http://localhost:8080/SupermarketSXManage/work/change.jsp',tType_id);
	}else{
		$('.input').val('');
	}
}

//添加操作
function workAdd(url){
	tType_work = '添加';
	
	dates();
	change(url);
	 dates();
	 
	 //数据交互
	 function dates(){
		 $.ajax({
			 url: "change",
			 type: "POST",
			 async: false,
			 dataType: "json",
			 data: {
				 'name':tType,
				 'work':tType_work
			 },
			 success: function(date){
				 var nameList = date.nameList;
				 var nameListChange = date.nameListChange;
				 tType_id = date.addNum;
				 
				 tType_name = nameList;
				 
				 add(nameListChange,nameList,tType_id);
			 }
		 })
		 //添加文本框
		 function add(nameListChange,nameList,tType_id){
			 
			 var html = '';
			 
			 html +="<tr><th>部门编号</th><th>部门名称</th><th>部门领导</th><th>部门信息</th></tr>";
			 html +="<tr>";
			 for(var i=0;i<nameListChange.length;i++){
				 if(i==0){
					 html += '<td><input type="text" type="'+nameList[i]+'" name="'+nameList[i]+'" class="input" id="'+nameList[i]+'" placeholder="'+tType_id+'" disabled></input></td>';
				 }else{
					 html += '<td><input type="text" type="'+nameList[i]+'" name="'+nameList[i]+'" class="input" id="'+nameList[i]+'" ></input></td>';
				 }
			 }
			 html +="</tr>";
			
			 $("#data_table_show").html(html);
		 }
	 }
}


/**
 * **********************************************************************
 * 缴费管理功能
 */
//获取下拉部门数据
function getdep(){
	tType_work = '显示';
	
	$.ajax({
		url: "work",
		type: "POST",
		dataType: "json",
		data:{
			'workType':tType_work
		},
		success:function(date){
			var dep_namelList = date['dep_namelLists'];
			
			var html = '';
			for(var i=0; i<dep_namelList.length; i++){
				html += '<option>';
				html += dep_namelList[i];
				html += '</option>';
			}
			
			document.getElementById("dep_namelList").innerHTML = html;
		}
	})
	
}

//查询所需部门信息**********************************************************************************
function workSearch(){
	search_type = document.getElementById("dep_namelList").value;
	var save_num = 0;
	$.ajax({
		url: "len",
		type: "POST",
		async: false,
		dataType: "json",
		data:{
			'search_type':search_type
		},
		success: function(date){
			save_num = date;
		}
	})
	
	var backurl = "'/SupermarketSXManage/work/payment.jsp'";
	var backtype = "'bill'";
	
	html = '<table class="data_table"><thead id="thead"></thead><tbody id="tbody"></tbody></table>';
	html += '<div id="button"><span onclick="dosave('+save_num+')"><input type="button" value="保存" ></input></span>';
	html += '<span onclick="getdep()"><input type="button" value="返回" onclick="ShowRight('+backurl+','+backtype+')"></input></span></div>';
	html += '<div class="pagination"><!-- 这里显示分页 --></div>';
	document.getElementById("content").innerHTML = html;
	
	showMsg();
	
}

function changeInput(id){
	var x = ((id+1)*4)-1;
	var html = '<input type="text" id="'+id+'" class="'+id+'" placeholder="请输入支票号"></input>	<input type="button" value="返回" onclick="backchose('+id+')"></input>';
	document.getElementById(x).innerHTML = html;
}

function backchose(id){
	var x = ((id+1)*4)-1;
	var html = '现金：	<input type="radio" name="'+id+'" value="现金" ></input>	支票：	<input type="radio" name="'+id+'" value="支票" onclick="changeInput('+id+')"></input>';
	document.getElementById(x).innerHTML = html;
}

//保存bill选择
function addContent(name){
	var obj = document.getElementsByName(name);
	for(var x=0; x<obj.length; x++){
		if(obj[x].checked){
			if(obj[x].value == '支票'){
				changeInput(name);
			}else{
				bill_content[name] = obj[x].value;
			}
		}
	}
}

//保存bill更改
function dosave(save_num){
	var string = new Array(save_num);
	
	var x = '';
	var stringValue;
	for(var i=0; i<save_num; i++){
		x = '';
		var obj = document.getElementsByName(i);
		for(var y=0; y<obj.length; y++){
			if(obj[y].checked){
				x = obj[y].value;
				string[i]=x;
			}
		}
		if(x == ''){
//			if(document.getElementsByClassName(i)){
//				stringValue = document.getElementsByClassName(i).value;
//				string[i]=stringValue;
//			}else{
//				string[i]=x;
//			}
			var lis = document.getElementsByTagName('input');
			for(var z=0; z<lis.length; z++){
				if(lis[z].className == i){
					stringValue = $('.'+i).val();
					string[i]=stringValue;
					break;
				}else{
					string[i]=x;
				}
			}
		}
		
	}

	
	tType_work = '保存';
	$.ajax({
		url:'work',
		data:{
			'workType':tType_work,
			'string':string,
			'search_type':search_type
		},
		dataType: "JSON",
		type: "POST",
		traditional: true,
		success: function(date){
			alert("支付账单成功");
		}
	});
	
	getdep();
	
	ShowRight('/SupermarketSXManage/work/payment.jsp', 'bill');
}